iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0

接續昨天小故事~~😊

在小鎮上,小精靈們的書店日益繁忙。這一天,他們希望能在評論中快速找到某個精靈看完書後的評論,但翻開所有評論尋找特定書本實在太耗時。為了提升查詢效率,小精靈們決定學習如何使用資料庫索引。哪什麼是 Database index 呢?

Database index (資料庫索引) 是什麼?

我們先來問問維基百科

database index is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional writes and storage space to maintain the index data structure. Indexes are used to quickly locate data without having to search every row in a database table every time said table is accessed. Indexes can be created using one or more columns of a database table, providing the basis for both rapid random lookups and efficient access of ordered records.

簡單說
資料庫索引就像一本書的目錄,能讓我們快速找到需要的資訊,省去每次翻整個資料表的麻煩。當然,也會占用一些額外的空間,並且在寫入資料時會稍微增加成本,但總體來說,索引讓查找和訪問資料變得更有效率,特別是當我們需要根據某些特定欄位來搜尋時。

好唷! 小精靈們已經知道,使用索引可以顯著提升查詢效能,避免像他在圖書館中那樣浪費時間。那我們就來看看如何實現 Database index!


1. 創建索引 (Creating Indexes)

創建 comments 資料表並在其中創建 book_id 欄位的索引,以加速查詢書籍的評論。

查詢效率:有了索引,當小精靈們查找某本書的評論時,資料庫可以快速定位到相關記錄,提升查詢性能。

Schema::create('comments', function (Blueprint $table) {
    $table->id(); // 評論ID
    $table->unsignedBigInteger('book_id'); // 書籍ID
    $table->text('content'); // 評論內容
    $table->timestamps(); // 時間戳記

    $table->index('book_id'); // 創建索引
});

2. 重新命名索引 (Renaming Indexes)

如果你想更改索引的名稱,以便於管理和理解,可以進行重新命名。

增加可讀性:更清晰的名稱可以讓小精靈們更容易理解索引的功能。

Schema::table('comments', function (Blueprint $table) {
    $table->renameIndex('comments_book_id_index', 'idx_comments_book_id'); 
});

3. 刪除索引 (Dropping Indexes)

當我們覺得某個索引不再需要或影響性能時,可以選擇刪除它。

性能考量:刪除不必要的索引可以減少資料庫的存儲需求,並提高寫入性能,特別是在頻繁進行插入或更新操作的情況下。

Schema::table('comments', function (Blueprint $table) {
    $table->dropIndex(['book_id']); // 刪除索引
});

4. 外鍵約束 (Foreign Key Constraints)

為了確保每個評論都關聯到一個有效的書籍,我們可以為 book_id 設置外鍵約束。

資料完整性:外鍵約束能確保評論只能關聯到存在的書籍,防止資料不一致。使用 onDelete('cascade') 還可以自動刪除與被刪除書籍相關的評論,保持資料庫的整潔。

Schema::table('comments', function (Blueprint $table) {
    $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
});

這些操作不僅提升了查詢性能,還增強了資料的完整性和結構的可讀性。在設計資料庫時,合理運用索引和外鍵約束對於提升應用的效能和可靠性至關重要。透過這些學習,小精靈們能夠更有效地管理書籍,讓書店的運作變得更加流暢。


參考資料:

  1. Laravel 11x - Indexes
  2. Wikipedia - Database index
  3. Powering Up Your Laravel App with Indexing in Database: A Comprehensive Guide
  4. Database indexing in Laravel - Everything you need to know

踏著身心靈的塔羅腳步,轉向技術與邏輯的工程師之路,就藉由塔羅日抽來紀錄今日的學習與生活吧!

錢幣皇后:提醒我們要具備充足的知識和技能,以應對挑戰。享受這段經歷,讓它成為珍貴的回憶,使我們在未來更加自信。

Life is an opportunity, benefit from it.
Life is beauty, admire it.
Life is a dream, realize it.

生命是一個機會,請善加把握;
生命是美的,應當細心欣賞;
生命是一場夢,勇敢去實現它。

— Mater Teresia


上一篇
Day8 - Laravel Migration
下一篇
Day10 - Laravel Database: Seeding
系列文
Laravel 隨筆學習札記13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言